package org.holynite.fieldmanage.Utils

import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder

import javax.crypto.Cipher
import javax.crypto.IllegalBlockSizeException
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.security.InvalidKeyException

/**
 * Created by midnite on 15/1/7.
 */
class SecurityEngine {
	private final String Algorithm = "AES/CBC/PKCS5Padding"
	private final String IVString = "y2xj64z86B*+VT;Z"

	private Cipher cipher
	private IvParameterSpec ivSpec
	private SecretKeySpec keySpec
	String key

	SecurityEngine() {
		cipher = Cipher.getInstance(Algorithm)
		ivSpec = new IvParameterSpec(IVString.bytes)
	}

	SecurityEngine(String key) {
		this()
		this.key = key
		translateKey()
	}

	private void translateKey() {
		byte[] keyByteTemp = key.bytes
		byte[] keyBytes = new byte[16]
		for (def i = 0; i < keyByteTemp.length && i < keyBytes.length; ++i) {
			keyBytes[i] = keyByteTemp[i]
		}
		keySpec = new SecretKeySpec(keyBytes, "AES")
	}

	String encrypt(String info) throws SecurityException {
		byte[] encrypted
		try {
			cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec)
			encrypted = cipher.doFinal(info.bytes)
		} catch (InvalidKeyException e) {
			throw new SecurityException(502, "Invalid key.")
		}
		new BASE64Encoder().encode(encrypted)
	}

	String decrypt(String info) throws SecurityException {
		byte[] decrypted
		try {
			cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec)
			decrypted = cipher.doFinal(new BASE64Decoder().decodeBuffer(info))
		} catch (InvalidKeyException e) {
			throw new SecurityException(502, "Invalid key.")
		} catch (IllegalBlockSizeException e) {
			throw new SecurityException(503, "Decryption failed. Possible wrong key.")
		}
		new String(decrypted)
	}

}
